import { Component, OnInit } from '@angular/core';
import {DutyService} from '../duty.service';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {ConfirmationService, Message} from 'primeng/primeng';
import {PUblicMethod} from '../../services/PUblicMethod';
import {ShiftObjModel} from '../shiftObj.model';
import {BasePage} from '../../base.page';
import {MessageService} from 'primeng/components/common/messageservice';

@Component({
  selector: 'app-setting-duty',
  templateUrl: './setting-duty.component.html',
  styleUrls: ['./setting-duty.component.scss']
})
export class SettingDutyComponent extends BasePage implements OnInit {

    scheduleDatas;
    display: boolean;
    zh: any;
    beginTime: Date = new Date();
    endTime: Date = new Date();
    dbeginTime:  Date = new Date();
    dendTime:  Date = new Date();
    shiftForm: FormGroup;
    fb: FormBuilder = new FormBuilder();
    applymsgs: Message[];
    msgPop: Message[];
    total: string;
    page_size: string;
    page_total: string;
    currentPage = '1';
    currentRow = '10';
    displayTime: boolean = false;
    shiftObj: ShiftObjModel;
    dialogHeader: string;
    disableForm: boolean = true;
    selectShifts: any;

    constructor(private dutyService: DutyService,
                public c: ConfirmationService,
                public m: MessageService) {
        super(c, m);
    }

    ngOnInit() {
        this.shiftObj = new ShiftObjModel();
        this.creatForm();
        this.shiftObj.status = '启用';
        this.shiftObj.shift_type = '单班次';
        this.display = false;
        this.shiftObj.overall_time = '0';
        this.shiftObj.color = '#f51313';
        this.zh = new PUblicMethod().initZh();
        this.beginTime = new Date();
        this.endTime = new Date();
        this.dbeginTime = new Date();
        this.dendTime = new Date();
        this.getSettings();
    }
    getSettings() {
        this.dutyService.getAllShiftQuery(this.currentPage, this.currentRow).subscribe(res => {
            this.scheduleDatas = res.items;
            console.log(res)
            this.total = res.page.total;
            this.page_size = res.page.page_size;
            this.page_total = res.page.page_total;
        });
    }
    creatForm() {
        this.shiftForm = this.fb.group({
            name: [null, Validators.required],
            sid: [null, Validators.required],
            beginTime: [null, Validators.required],
            endTime: [null, Validators.required],
            dbeginTime: [null, Validators.required],
            dendTime: [null, Validators.required]
        });
    }
    isFieldValid(field: string) {
        return !this.shiftForm.get(field).valid && this.shiftForm.get(field).touched;
    }
    validateAllFormFields(formGroup: FormGroup) {
        Object.keys(formGroup.controls).forEach(field => {
            const control = formGroup.get(field);
            if (control instanceof FormControl) {
                control.markAsTouched({onlySelf: true});
            }else if (control instanceof  FormGroup) {
                this.validateAllFormFields(control);
            }
        });
    }
    dbshift(type) {
        (type === 'sg') && (this.displayTime = false);
        (type === 'db') && (this.displayTime = true);
    }
    displayDialog(type?: string) {
        this.shiftForm.get('name').enable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('sid').enable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('beginTime').enable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('endTime').enable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('dbeginTime').enable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('dendTime').enable({onlySelf: true, emitEvent: true});
        if (type === 'add') {
            this.dialogHeader = '新增班次';
            this.shiftObj.name = '';
            this.shiftObj.sid = '';
            this.shiftObj.shift_type = '单班次';
            this.beginTime = new Date();
            this.endTime = new Date();
            this.dbeginTime = new Date();
            this.dendTime = new Date();
            this.shiftObj.overall_time = '0';
            this.shiftObj.color = '#f51313';
            this.shiftObj.status = '启用';
            this.creatForm();
        }
        if (type === 'edit') {
            this.dialogHeader = '编辑班次';
        }
        if (type === 'view') {
            this.dialogHeader = '查看班次'
        };
        this.display = true;
    }
    requestAddShift(obj: ShiftObjModel): void {
        this.dutyService.addDiyShift(obj).subscribe(res => {
            if (res === '00000') {
                this.msgPop = [];
                this.msgPop.push({severity: 'success', summary: '消息提示', detail: '班次新增成功'});
                this.display = false;
                this.getSettings();
            }else {
                this.msgPop = [];
                this.msgPop.push({severity: 'error', summary: '提示消息', detail: '班次新增失败' + '\n' + res });
            }
        });
    }
    cancel(){
      this.msgPop = [];
      this.display = false;
    }
    requestEditShift(obj: ShiftObjModel): void {
        this.dutyService.editDiyShift(obj).subscribe(res => {
            if (res === '00000') {
                this.msgPop = [];
                this.msgPop.push({severity: 'success', summary: '消息提示', detail: '班次编辑成功'});
                this.display = false;
                this.getSettings();
            }else {
                this.msgPop = [];
                this.msgPop.push({severity: 'error', summary: '提示消息', detail: '班次编辑失败' + '\n' + res });
            }
        });
    }
    formateTime() {
        this.shiftObj.end_time_1 = PUblicMethod.formateMiniteTime(this.endTime);
        this.shiftObj.begin_time_1 = PUblicMethod.formateMiniteTime(this.beginTime);
        this.shiftObj.end_time_2 = PUblicMethod.formateMiniteTime(this.dendTime);
        this.shiftObj.begin_time_2 = PUblicMethod.formateMiniteTime(this.dbeginTime);
    }
    addshift(): void{
        this.formateTime();
        if (!this.displayTime && this.shiftObj.sid && this.shiftObj.name) {
            this.shiftObj.begin_time_2 = '';
            this.shiftObj.end_time_2 = '';
            (this.dialogHeader === '新增班次') && ( this.requestAddShift(this.shiftObj));
            (this.dialogHeader === '编辑班次') && (this.requestEditShift(this.shiftObj));
        }else if (this.displayTime && this.shiftObj.sid && this.shiftObj.name){
            (this.dialogHeader === '新增班次') && ( this.requestAddShift(this.shiftObj));
            (this.dialogHeader === '编辑班次') && (this.requestEditShift(this.shiftObj));
        }else {
            this.validateAllFormFields(this.shiftForm);
        }
    }
    editShifts(shift) {
        this.displayDialog('edit');
        this.shiftForm.get('name').enable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('sid').enable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('beginTime').enable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('endTime').enable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('dbeginTime').enable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('dendTime').enable({onlySelf: true, emitEvent: true});
        this.shiftObj = new ShiftObjModel(shift);
        this.beginTime = new Date(PUblicMethod.formateEnrtyTime(PUblicMethod.formateTimeToEntryTime(shift.begin_time_1)));
        this.endTime = new Date (PUblicMethod.formateEnrtyTime(PUblicMethod.formateTimeToEntryTime(shift.end_time_1)));
        this.dispalyDoubleTime(shift);
    }
    dispalyDoubleTime(shift) {
        if (this.shiftObj.shift_type === '两头班') {
            this.displayTime = true;
            this.dbeginTime = new Date(PUblicMethod.formateEnrtyTime(PUblicMethod.formateTimeToEntryTime(shift.begin_time_2)));
            this.dendTime = new Date (PUblicMethod.formateEnrtyTime(PUblicMethod.formateTimeToEntryTime(shift.end_time_2)));
        }
    }
    freezeOrUnfreeze(shift) {
        let msg = '';
        (shift.status === '启用') && (msg = '确认冻结吗？');
        (shift.status === '冻结') && (msg = '确认启用吗？');
        this.c.confirm({
           message: msg,
           accept: () => {
                if (shift.status === '启用') {
                   shift.status = '冻结';
                }else if (shift.status === '冻结') {
                   shift.status = '启用';
                }
                this.dutyService.freezeOrUnfreezeDiyShift(shift).subscribe(res => {

                  if(res === '00000'){
                    this.alert('操作成功');
                    this.getSettings();
                  }else{
                    this.alert(`操作失败 + ${res}`, 'error')
                    this.getSettings();
                  }
                   // (res === '00000') && (this.alert('操作成功'));
                   // (!(res === '00000')) && (this.alert(`操作失败 + ${res}`, 'error'));

                });
           },
           reject: () => {

           }
        });
    }
    view(shift) {
      this.markedAdUntouded();
        this.displayDialog('view');
        this.shiftObj = new ShiftObjModel(shift);
        this.beginTime = new Date(PUblicMethod.formateEnrtyTime(PUblicMethod.formateTimeToEntryTime(shift.begin_time_1)));
        this.endTime = new Date (PUblicMethod.formateEnrtyTime(PUblicMethod.formateTimeToEntryTime(shift.end_time_1)));
        this.dispalyDoubleTime(shift);
        this.shiftForm.get('name').disable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('sid').disable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('beginTime').disable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('endTime').disable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('dbeginTime').disable({onlySelf: true, emitEvent: true});
        this.shiftForm.get('dendTime').disable({onlySelf: true, emitEvent: true});
        // this.shiftForm.get('shift_type').disable({onlySelf: true, emitEvent: true});
        // this.shiftForm.get('status').disable({onlySelf: true, emitEvent: true});
        this.disableForm = false;
    }
    markedAdUntouded = () => {
        this.shiftForm.get('name').markAsUntouched({onlySelf: true});
        this.shiftForm.get('beginTime').markAsUntouched({onlySelf: true});
        this.shiftForm.get('endTime').markAsUntouched({onlySelf: true});
        this.shiftForm.get('dbeginTime').markAsUntouched({onlySelf: true});
        this.shiftForm.get('dendTime').markAsUntouched({onlySelf: true});
    };
    deleteShifts(shift) {
        this.c.confirm({
            message: '确认删除吗?',
            accept: () => {
                this.dutyService.deletDiyShift([shift.sid]).subscribe(res => {
                   if (res === '00000') {
                       this.msgPop = [];
                       this.msgPop.push({severity: 'success', summary: '消息提示', detail: '班次删除成功'});
                      this.getSettings();
                   }else {
                       this.msgPop = [];
                       this.msgPop.push({severity: 'error', summary: '提示消息', detail: '班次删除失败' + '\n' + res });
                   }
                });
            }
        });
    }
    computeTime(){
        let datas = this.endTime.getTime() - this.beginTime.getTime();
        // 计算出小时数
        let leave1 = datas % (24 * 3600 * 1000);    // 计算天数后剩余的毫秒数
        let hours = Math.floor(leave1 / (3600 * 1000));
        // 计算相差分钟数
        let leave2 = leave1 % (3600 * 1000);        // 计算小时数后剩余的毫秒数
        let minutes = Math.floor(leave2 / (60 * 1000));
        // 计算相差秒数
        let leave3 = leave2 % (60 * 1000);      // 计算分钟数后剩余的毫秒数
        let seconds = Math.round(leave3 / 1000);
        // console.log(" 相差 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒");
        this.shiftObj.overall_time = hours + '小时 ' + minutes + ' 分钟' + seconds + ' 秒';
    }
    paginate(event) {
        this.currentPage = (event.page + 1).toString();
        this.currentRow = event.rows.toString();
        this.dutyService.getAllShiftQuery((event.page + 1).toString(), event.rows.toString()).subscribe( res => {
            this.scheduleDatas = res.items;
            this.total = res.page.total;
            this.page_size = res.page.page_size;
            this.page_total = res.page.page_total;
        });
    }
    onHide() {
        this.display = false;
        this.displayTime = false;
        this.disableForm = true;
    }
}
